<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/23
 * Time: 9:27
 */

namespace app\api\model;
use app\common\lib\exception\ApiException;
use think\Model;
use think\Log;
use think\Db;

class StudentStopLesson extends Model
{
    /**
     * @学生申请停课
     */
    public function addStuStopLes(){

        if(empty($_POST)){
            throw new ApiException('数据不合法',404);
        }
        //les_id int 申请停课id即课程详情id 必传
        if(empty($_POST['les_id'])){
            throw new ApiException('les_id is not found',404);
        }
        //student_id int 学生id 申请停课的学生
        if(empty($_POST['student_id'])){
            throw new ApiException('student_id is not found',404);
        }
        //stu_content string 申请停课原因
        if(empty($_POST['stu_content'])){
            throw new ApiException('stu_content is not found',404);
        }
        try{
            //$les_id = $_POST['les_id'];
            //return show(config('code.error'),'！',$les_id);
            $les_id = json_decode($_POST['les_id']);
            //return show(config('code.error'),'！',$les_id);
            $rec = [];
            foreach($les_id as $k => $v){
                //return show(config('code.error'),'！',$v);
                $lesson = Db::name("lesson")->where('id',$v)->find();
                //return show(config('code.error'),'！',$lesson);
                if($lesson['lesson_num'] == $lesson['com_lesson_num']){
                    return show(config('code.error'),'有课程已结课,不可发起停课！');
                }
                $data['stu_id'] = $_POST['student_id'];
                $data['les_id'] = $les_id[$k];
                $data['stu_content'] = $_POST['stu_content'];

                $info = Db::name('student_stop_lesson')
                    ->where('stu_id',$data['stu_id'])
                    ->where('les_id',$data['les_id'])
                    ->where('stu_content',$data['stu_content'])
                    ->find();
                if(!$info){
                    $rec[$k] = $data;
                }else{
                    return show(config('code.error'),'您提交的信息有待审核项，请核实后提交');
                }

            }
                //return show(config('code.success'),'！',$rec);
            foreach($rec as $x => $y) {
                $rec[] = Db::name('student_stop_lesson')->insert($y);
            }

            return show(config('code.success'),'申请成功,请等待审核！');

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }
}